using System;
using System.Threading.Tasks;
using System.Windows.Media;

namespace DocumentCreationSystem.Controls
{
    public partial class DocumentEditor
    {
        /// <summary>
        /// 定位到指定行列（不加载文件）
        /// </summary>
        public void NavigateTo(int line, int column)
        {
            if (TextEditor == null || TextEditor.Document == null) return;
            if (line < 1) line = 1;
            if (line > TextEditor.LineCount) line = TextEditor.LineCount;

            try
            {
                var lineObj = TextEditor.Document.GetLineByNumber(line);
                var offset = lineObj.Offset + Math.Max(0, column - 1);
                if (offset > TextEditor.Document.TextLength)
                    offset = TextEditor.Document.TextLength;

                TextEditor.CaretOffset = offset;
                TextEditor.Select(offset, 0);
                TextEditor.ScrollTo(line, Math.Max(1, column));
            }
            catch
            {
                // 忽略定位异常，避免影响主流程
            }
        }

        /// <summary>
        /// 打开文件并定位到指定行列
        /// </summary>
        public async Task OpenAndNavigateAsync(string filePath, int line, int column)
        {
            await LoadDocumentAsync(filePath);
            // 略微延迟，确保渲染完成后定位更稳
            await Task.Delay(50);
            NavigateTo(line, column);
        }
    }
}

